#!/usr/bin/env bash
cd `dirname $0`

# 默认macOS
OS=darwin
ARCH=amd64
MOD=code_gen
NAME=code_gen
if [ "" != "$1" ];then
  OS=$1
fi
if [ "" == "$2" ];then
  ARCH=$2
fi
if [ "" != "$3" ];then
  MOD=$3
fi
if [ "" != "$4" ];then
  NAME=$4
fi

export GO111MODULE=on
export GOOS=$OS
export GOARCH=$ARCH
export CGO_ENABLED=1
# c 编译选项
#export CGO_CFLAGS=

# CGO交叉编译
# https://blog.csdn.net/weixin_42662249/article/details/116743543
if [ "1" == "$CGO_ENABLED" ];then
  # CGO交叉编译 windows
  # 需要安装 mingw-w64
  # brew install mingw-w64
  if [ "windows" == $OS ]; then
    export CC=x86_64-w64-mingw32-gcc
    export CXX=x86_64-w64-mingw32-g++
  fi
  # CGO交叉编译 linux
  # 需要安装 FiloSottile/musl-cross/musl-cross
  # brew install FiloSottile/musl-cross/musl-cross
  if [ "linux" == $OS ];then
    export CC=x86_64-linux-musl-gcc
    export CXX=x86_64-linux-musl-g++
  fi
fi

rm -rf $NAME

# -gcflags=all="-N -l" 不做编译优化，确保程序崩溃能把信息coredump出来 按需添加
# -ldflags "-s -w" 删除符号和debug信息 编译优化
# -tags=jsoniter gin框架json解析器
go mod tidy
go build -tags=jsoniter -ldflags="-s -w -extldflags=-static" -o ./${NAME} ${MOD}


# 要压缩的脚本
SCRIPTS='start.sh stop.sh'
if [ "windows" == $OS ]; then
  SCRIPTS='start.bat'
fi

rm -rf $MOD.zip

ZIP_FILE="$NAME $SCRIPTS config*.yaml"
echo $ZIP_FILE
zip -r9 $MOD.zip $ZIP_FILE
